package cn.org.donald.framework.controller;

import cn.org.donald.framework.service.SysPermissionService;
import cn.org.donald.framework.pojo.dto.MiniDto;
import cn.org.donald.framework.pojo.dto.SwaggerDto;
import cn.org.donald.framework.pojo.dto.TagDto;
import cn.org.donald.framework.pojo.vo.ControllerPermissionVo;
import cn.org.donald.framework.pojo.vo.HttpResult;
import cn.org.donald.framework.pojo.vo.TableResult;
import cn.org.donald.pojo.entity.Permission;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ： Donald
 * @date ： 2020/11/3 23:03
 * @description： 同步接口只有admin管理员有权限 不需要添加角色权限
 */
@RestController
@RequestMapping("/api")
@RequiresRoles("admin")
public class ApiController extends BaseController {

    @Autowired
    private SysPermissionService sysPermissionService;


    @PostMapping("/sync")
    public HttpResult show(@RequestBody SwaggerDto swaggerDto){
        Map<String, Map<String, MiniDto>> pathDtoMapList = swaggerDto.getPaths();
        List<TagDto> tagsList = swaggerDto.getTags();
        List<Permission> pathList = new ArrayList<>();

        pathDtoMapList.forEach((k,v) -> v.forEach((k2, v2) -> {
            Permission permission = new Permission();
            permission.setUrl(k);
            permission.setType(k2);
            permission.setControllerCode(v2.getTags()[0]);
            permission.setDescription(v2.getSummary());

            //字符串操作设置permissionName
            String url = k.startsWith("/")? k.substring(1):k;
            if (url.contains("{")){
                url = url.substring(0,url.indexOf("{"));
            }
            String s = url.replaceAll("/",":");
            String permissionName = s.endsWith(":") ? s + k2 : s + ":" + k2;
            permission.setPermissionName(permissionName);
            pathList.add(permission);
        }));

        int rows = sysPermissionService.syncApi(pathList,tagsList);
        return toResultSuccess("同步成功");
    }

    @PostMapping("/list")
    public TableResult getList(){
        List<ControllerPermissionVo> controllerPermissionVos =  sysPermissionService.findTree(null);
        return toTableResult(controllerPermissionVos);
    }
}
